import React, { useReducer, createContext } from 'react';

// 1. 创建全局的Context
const FlowContext = createContext();

export default FlowContext;

// 2. 创建全局的Reducer
const initState = {
  graph: {
    nodes: [],
    edges: [],
  },
  readOnly: false,
  hasStartNode: false,
  hasEndNode: false
};

function reducer(state, action) {
  const { graph } = state;
  const { nodes } = graph;
  const { type, payload } = action;

  if (type === 'update_flow_data') {
    return {
      ...state,
      ...payload,
    };
  }

  if (type === 'update_node') {
    const { id, ...rest } = payload;
    const index = nodes.findIndex(node => node.id === id);
    let newNodes;
    if (index !== -1) {
      newNodes = nodes.map(node => (node.id === id ? { ...node, ...rest } : node));
    } else {
      newNodes = [...nodes, { id, ...rest }];
    }
    return {
      ...state,
      graph: {
        ...graph,
        nodes: newNodes,
      },
    };
  }

  throw new Error();
}

// 3. 将全局useReducer返回的state和dispatch传递给全局Context.Provider的value中
export const FlowProvider = ({ value = {}, children }) => {
  const [state, dispatch] = useReducer(reducer, initState);

  return (
    <FlowContext.Provider value={{ state: { ...state, ...value }, dispatch }}>
      {children}
    </FlowContext.Provider>
  );
};
